package com.cloud.servicezuul.compoment;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * 使用令牌桶进行限流  这是网关限流
 */
@SuppressWarnings("all")
@Component
public class LimitFilter extends ZuulFilter {

    private static final RateLimiter RATE_LIMITER = RateLimiter.create(10);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //限流操作是最先执行的过滤器，所以这里的顺序要最小，数值越小，越最先执行
        return Integer.MIN_VALUE;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        if (RATE_LIMITER.tryAcquire()){
            //拿到令牌，执行业务逻辑
        }else {
            //没有拿到令牌，执行拒绝或重试业务逻辑
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
        }

        return null;
    }
}
